// ==UserScript==
// @name         UC云盘助手 JAE
// @namespace    hhttp://git.oschina.net/jae/tampermonkeyScripts
// @version      0.1
// @description  UC云盘助手，,交流QQ群:123266961
// @author       Jaeger <hj.q@qq.com>
// @match        http://disk.yun.uc.cn/*
// @grant        none
// @icon http://disk.yun.uc.cn//favicon.ico
// @run-at         document-end
// ==/UserScript==

window.UC = {
	init: function(){
		this.ajaxUrl = "http://disk.yun.uc.cn/netdisk/ajaxnd?type=all";
		this.data = {};
		this.handle = "";
	},
	getParam: function(){
		var hash = document.location.hash;
		var split = hash.split("/");
		return split[1];
	},
	getData: function(){
		var _this = this;
		$.getJSON(this.ajaxUrl,{_:+new Date(),dirid:this.getParam()},function(data){
			_this.data = _this.bulidData(data);
			_this.handle = window.setInterval(_this.scan,1000);
		});
	},
	bulidData: function(data){
		var rtData = {};
		for(i in data.filelist){
			 rtData["id" + data.filelist[i]['id']] = data.filelist[i];
		}
		return rtData;
	},
	getDownloadUrl: function($this){
		var id = "id" + $this.attr("id");
		return this.data[id].download;
	},
	scan: function(){
		var _this = this;
		$("#netdiskListScrollPane tr[type!=dir]").each(function(){
				var isExist = $(this).find("#jae").length;
				if(!isExist){
					var url = _this.getDownloadUrl($(this));
					$(this).find("td:eq(1)>span:eq(0)").removeAttr('style');
					$(this).find("td:eq(1)").append('<span id="jae"><input type="text" value="' + url + '" id="url_input" /><button type="button" class="button" onClick="UC.copyTextToClipboard(\''+url+'\')" >复制</button><a href="'+url+'" download><button type="button" class="button"  >下载</button></a></span>');
				}
		});
	},
	copyTextToClipboard: function (text) {
	  var textArea = document.createElement("textarea");
	  textArea.style.position = 'fixed';
	  textArea.style.top = 0;
	  textArea.style.left = 0;
	  textArea.style.width = '2em';
	  textArea.style.height = '2em';
	  textArea.style.padding = 0;
	  textArea.style.border = 'none';
	  textArea.style.outline = 'none';
	  textArea.style.boxShadow = 'none';
	  textArea.style.background = 'transparent';
	  textArea.value = text;
	  document.body.appendChild(textArea);
	  textArea.select();
	  try {
	    var successful = document.execCommand('copy');
	    var msg = successful ? 'successful' : 'unsuccessful';
	    console.log('Copying text command was ' + msg);
	  } catch (err) {
	    console.log('Oops, unable to copy');
	  }
	  document.body.removeChild(textArea);
	},
	run: function(){
		_this = this;
		this.init();
		this.getData();
		$("#leftnav a").bind("click",function(){
			window.clearInterval(_this.handle);
			_this.getData();
		});
		$("#netdiskListScrollPane").on("click","[type=dir]",function(){
			console.log("assad");
			window.clearInterval(_this.handle);
			_this.getData();
		});
	}
}
UC.run();